const axios = require('axios');
const cozeToken = require('./cozeToken');

// 创建空会话
async function conversationCreate() {
	try {
		const headers = await cozeToken.getAuthHeaders();
		const response = await axios.post('https://api.coze.cn/v3/conversation/create', {}, {
			headers: headers
		});
		return response;
	} catch (error) {
		console.error('创建会话失败:', error);
		throw error;
	}
}

// 发送消息
async function sendCozeChat(msg) {
	try {
		const headers = await cozeToken.getAuthHeaders();
		const response = await axios.post('https://api.coze.cn/v3/chat', {
			"bot_id": "7428843129602080795",
			"user_id": 'yuanlj',
			"stream": false,
			"auto_save_history":true,
			"additional_messages": [
				{
					"role": "user",
					"content": msg,
					"content_type": "text"
				}
			]
		}, {
			headers: headers
		});
		return response;
	} catch (error) {
		console.error('发送消息失败:', error);
		throw error;
	}
}

// 获取消息
async function fetchCozeChatRetrieve(chat_id) {
	try {
		const headers = await cozeToken.getAuthHeaders();
		const response = await axios.get(`https://api.coze.cn/v3/chat/${chat_id}/retrieve`, {
			headers: headers
		});
		return response;
	} catch (error) {
		console.error('获取消息失败:', error);
		throw error;
	}
}

// 获取消息列表
async function fetchCozeChatMessageList(chat_id) {
	try {
		const headers = await cozeToken.getAuthHeaders();
		const response = await axios.get(`https://api.coze.cn/v3/chat/${chat_id}/messages`, {
			headers: headers
		});
		return response;
	} catch (error) {
		console.error('获取消息列表失败:', error);
		throw error;
	}
}

// 发送流式消息
async function sendCozeChatStream(msg) {
	try {
		const headers = await cozeToken.getAuthHeaders();
		const response = await axios.post('https://api.coze.cn/v3/chat', {
			"bot_id": "7428843129602080795",
			"user_id": 'yuanlj',
			"stream": true,
			"auto_save_history":true,
			"additional_messages": [
				{
					"role": "user",
					"content": msg,
					"content_type": "text"
				}
			]
		}, {
			headers: headers,
			responseType: 'stream'
		});
		return response;
	} catch (error) {
		console.error('发送流式消息失败:', error);
		throw error;
	}
}

module.exports = {
	conversationCreate,
	sendCozeChat,
	fetchCozeChatRetrieve,
	fetchCozeChatMessageList,
	sendCozeChatStream
};